package com.inspectortime.webapp.inspector.fee;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.OptionalService;
import com.inspectortime.repository.Factory;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class OptionalServiceFormController extends SimpleFormController {

	private Factory factory;

	public void setFactory(Factory factory) {
		this.factory = factory;
	}

	private Repository repository;

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		return data;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		OptionalService service = null;
		String id = request.getParameter("id");
		if (id != null && id.length() > 0) {
			service = repository.loadOptionalService(id);
		} else {
			service = factory.createOptionalService();
		}
		return service;
	}

	protected ModelAndView onSubmit(
			HttpServletRequest request,	HttpServletResponse response, Object command,	BindException errors)
			throws Exception {

		OptionalService service = (OptionalService) command;
		
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		if (!company.getOptionalServices().contains(service)) {
			service.save();
			company.getOptionalServices().add(service);
			service.setCompany(company);
			company.save();				
		} else {
			service.save();
		}
		
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		return mv;
	}

}
